<!--
 * @Author: Wanko
 * @Date: 2023-08-17 10:52:22
 * @LastEditors: Wanko
 * @LastEditTime: 2024-01-19 18:55:33
 * @Description: this._id.toString();
-->
<template>
  <div class="h-screen p-30">
    <el-carousel
    type="card"
    :initial-index="initialIndex"
    @change="changeCarousel"
    :autoplay="false"
    :loop="true"
  >
    <el-carousel-item v-for="(i, idx) in carouselList" class="shadow bg-f8 h-full">
      {{ idx }}
      <div class="p-30 flex-cc">{{ i.content }}</div>
    </el-carousel-item>
  </el-carousel>
  </div>
  
</template>
<script>
// 引入loadsh
import _ from 'lodash'
import request from '@/request'
import hotkeys from 'hotkeys-js'
import axios from 'axios'

export default {
  data() {
    return {
      visible: false,
      content: '',
      fileList: [],
      cards: [],
      list: [],
      dialogVisible: false,
      searchQuery: '',
      searchList: [],
      uploading: false,
      assignNumber: 1,
      shortcuts: {
        'command+/': this.focusInput,
        'command+enter': this.onSubmit
        // 可以继续添加其他快捷键和对应的操作函数
      },
      inputFocused: false,
      carouselList: [],
      initialIndex: 2
    }
  },
  created() {
    // 使用防抖函数包装 performSearch 方法，延迟执行 500 毫秒
    this.debouncedSearch = this.debounce(this.onSearch, 500)

    this.getList()

    // this.loadMarkdownFile();
  },
  async mounted() {
    // try {
    //   let response
    //   if(process.env.NODE_ENV === 'development') {
    //     response = await fetch('/public/金句.md')
    //   }else {
    //     response = await fetch('https://www.wanko.top/public/金句.md')
    //   }

    //   if (response.ok) {
    //     const markdownContent = await response.text() // 获取static目录下所有文件名
    //     console.log(markdownContent)
    //     const paragraphs = markdownContent.split('\n\n') // 根据空行分割段落

    //     console.log('段落数组:', paragraphs)

    //     const cards = paragraphs.map((i) => {
    //       return {
    //         content: i
    //       }
    //     })
    //     this.cards = _.shuffle(cards)
    //     this.allCards = this.cards
    //   }
    // } catch (error) {}
    const fileInput = document.getElementById('fileInput')
    // fileInput.addEventListener('change', (event) => {
    //   const file = event.target.files[0];

    //   console.log(file)
    //   if (file.size) {
    //     const reader = new FileReader();
    //     // 定义 FileReader 的 onload 事件处理函数
    //     reader.onload = function (event) {
    //       console.log(event)
    //       const markdownText = event.target.result;
    //       console.log(markdownText)
    //       // 将 Markdown 内容显示在页面上
    //       // markdownContentElement.textContent = markdownText;
    //     };

    //     // 使用 FileReader 读取文件内容
    //     reader.readAsText(file);
    //   }
    // });
    Object.entries(this.shortcuts).forEach(([shortcut, callback]) => {
      this.handleShortcuts(shortcut, callback)
    })
    // hotkeys('command+/', (event, handler) => {
    //   // 阻止默认行为（避免触发浏览器的搜索）
    //   console.log('11111')
    //   // 聚焦到 el-input
    //   this.$refs.contentRef.focus()
    // })

    // hotkeys('command+enter', (event, handler) => {
    //   console.log('commandcommandcommandcommand', event)
    //   // 阻止默认行为（避免触发浏览器的提交表单）
    //   // 调用 el-button 的提交方法
    //   this.onSubmit()
    // })
    window.addEventListener('keydown', this.handleGlobalShortcut)
  },
  beforeDestroy() {
    // 遍历快捷键对象，动态移除全局快捷键监听
    Object.keys(this.shortcuts).forEach((shortcut) => {
      hotkeys.unbind(shortcut)
    })
  },
  methods: {
    changeCarousel(idx) {
      console.log(idx, this.carouselList.length)
      if (idx === this.carouselList.length - 1) {
        //
        console.log('最后一个元素')
        this.carouselList = [...this.carouselList, ...this.getRandom(1)]
        this.initialIndex = idx
      }
      // if (idx === 1) {
      //   //
      //   console.log('第一个元素')
      //   this.carouselList = [...this.getRandom(1), ...this.carouselList]
      //   this.initialIndex = idx
      // }
      // this.initialIndex = idx

      console.log(idx)
    },
    async onDelete(i) {
      console.log(i)
      const { id } = i
      console.log(id)
      await request.delete(`/${id}`)
      this.$message.success('删除成功')
      this.visible = false
      this.getList()
    },
    handleGlobalShortcut(event) {
      // 获取当前活动的 DOM 元素
      const activeElement = document.activeElement

      // 判断当前焦点是否在输入框内或者输入框的子元素中
      const isInputFocused =
        activeElement && (activeElement.tagName === 'INPUT' || activeElement.tagName === 'TEXTAREA')

      console.log(isInputFocused)
      if (isInputFocused) {
        if (event.metaKey && event.key === 'Enter') {
          event.preventDefault()
          this.onSubmit()
        }
      }

      // // 如果焦点不在输入框内，则执行你期望的全局快捷键操作
      // if (!isInputFocused) {
      //   if (event.metaKey && event.key === '/') {
      //     event.preventDefault();
      //     this.focusInput();
      //   } else if (event.metaKey && event.key === 'Enter') {
      //     event.preventDefault();
      //     this.submitForm();
      //   }
      // }
    },

    handleShortcuts(action, callback) {
      hotkeys(action, (event, handler) => {
        // 阻止默认行为
        const activeElement = document.activeElement

        // 如果当前焦点不在 el-input 中，执行你期望的全局快捷键操作
        if (
          !activeElement ||
          (activeElement.tagName !== 'INPUT' && activeElement.tagName !== 'TEXTAREA')
        ) {
          // event.preventDefault()
          callback()
        }
      })
    },
    focusInput() {
      console.log('1111')
      // 聚焦到 el-input
      console.log(this.$refs.contentRef)
      this.$refs.contentRef.focus()
    },
    submitForm() {
      // 调用 el-button 的提交方法
      this.$refs.submitRef.click()
    },
    async onSubmit() {
      if (!this.content) return this.$message.error('请输入内容')
      try {
        await request.post('/', { content: this.content })
        this.$message.success('提交成功')
        this.content = ''
        this.getList()
      } catch (error) {
        console.log(error, 'error')
        this.$message.error(error)
      }
    },
    async getList() {
      const cards = await request.get('/')
      this.cards = cards.map((i) => ({ ...i, showOperate: false }))

      this.cards = _.shuffle(this.cards)
      this.allCards = this.cards

      this.carouselList = this.getRandom(10)
    },
    async loadMarkdownFile() {
      try {
        // 使用 Webpack 的 require.context 来导入 .md 文件
        const markdownFileContext = require.context('./', false, /\.md$/)

        const paragraphs = markdownFileContext.split('\n\n') // 根据空行分割段落

        console.log('段落数组:', paragraphs)

        this.cards = paragraphs.map((i) => {
          return {
            content: i
          }
        })
      } catch (error) {
        console.error('无法加载 Markdown 文件：', error)
      }
    },
    handleFileUpload(event) {
      const fileInput = this.$refs.fileInput
      if (fileInput.files.length > 0) {
        const uploadedFile = fileInput.files[0]
        console.log(uploadedFile)
        if (uploadedFile.size) {
          const reader = new FileReader()
          reader.onload = (event) => {
            // 获取文件内容
            const fileContent = event.target.result
            console.log('文件内容:', fileContent)
            const paragraphs = fileContent.split('\n\n') // 根据空行分割段落
            console.log('段落数组:', paragraphs)

            this.cards = paragraphs.map((i) => {
              return {
                content: i
              }
            })
            // 在这里处理文件内容
            // 你可以将文件内容存储在 Vue 组件的数据中或进行其他处理
          }
          reader.readAsText(uploadedFile)
        } else {
          console.error('仅支持上传 .txt 文件')
        }
      }
    },

    onSearch() {
      if (!this.searchQuery) return (this.cards = this.allCards)
      const searchList = this.cards.filter((item) => {
        return item.content.includes(this.searchQuery)
      })
      this.cards = searchList

      // console.log(this.searchList)
    },
    debounce(func, delay = 500) {
      let timer
      return function () {
        const context = this
        const args = arguments
        clearTimeout(timer)
        timer = setTimeout(() => {
          func.apply(context, args)
        }, delay)
      }
    },
    async onCardCopy(content) {
      try {
        await navigator.clipboard.writeText(content)
        this.$message.success('复制成功')
      } catch (error) {
        this.$message.error('复制失败')
      }
      return
      const textArea = document.createElement('textarea')
      textArea.value = content
      document.body.appendChild(textArea)
      textArea.select()

      try {
        document.execCommand('copy')
        this.$message.success('Content copied to clipboard')
      } catch (error) {
        this.$message.error('Error copying content')
      }

      document.body.removeChild(textArea)
    },
    onCopy() {
      console.log('copy')
      const element = document.querySelector('.card-text')
      console.log(element)
      this.copyAllPTagsText('.card-text')
    },
    onClick() {
      const maxLength = this.cards.length
      console.log(this.random(0, maxLength))
    },
    copyAllPTagsText(parentElementId) {
      // 获取父元素
      const parentElement = document.querySelector(parentElementId)

      // 获取所有 <p> 标签
      const pTags = parentElement.getElementsByTagName('p')

      // 创建一个文本区域用于保存文本内容
      const textarea = document.createElement('textarea')
      let copiedText = ''

      // 遍历 <p> 标签并将文本内容添加到 copiedText
      for (let i = 0; i < pTags.length; i++) {
        copiedText += pTags[i].textContent + '\n'
      }

      // 将文本内容设置到文本区域
      textarea.value = copiedText

      // 将文本区域添加到页面以便选择文本
      document.body.appendChild(textarea)

      // 选择文本并复制到剪贴板
      textarea.select()
      try {
        const successful = document.execCommand('copy')
        if (successful) {
          this.$message.success('文本已成功复制到剪贴板！')
        } else {
          alert('复制失败，请手动复制文本。')
        }
      } catch (err) {
        alert('复制失败，请手动复制文本。')
      } finally {
        // 删除文本区域
        document.body.removeChild(textarea)
      }
    },
    onAssignNumber() {
      this.onGenerate(this.assignNumber)
    },
    // 随机生成卡片
    onSwitch() {
      this.onGenerate(30)
    },
    getRandom(number) {
      const maxLength = this.cards.length - 1
      const randomNumbers = this.getRandomUniqueNumbers(0, maxLength, number)
      return randomNumbers.map((i) => {
        return this.cards[i]
      })
    },
    onGenerate(number) {
      const maxLength = this.cards.length - 1
      const randomNumbers = this.getRandomUniqueNumbers(0, maxLength, number)
      console.log(randomNumbers)

      const list = randomNumbers.map((i, index) => {
        const item = this.cards[i]
        return `${index + 1}、${item.content}`
      })
      this.list = list
      this.dialogVisible = true
      console.log(list)
    },
    getRandomUniqueNumbers(min, max, count) {
      if (count > max - min + 1) {
        throw new Error('Count must be less than or equal to the range of numbers.')
      }

      const uniqueNumbers = new Set()

      while (uniqueNumbers.size < count) {
        const randomNumber = Math.floor(Math.random() * (max - min + 1)) + min
        uniqueNumbers.add(randomNumber)
      }

      return Array.from(uniqueNumbers)
    },
    random(min, max) {
      if (min >= 0 && max > 0 && max >= min) {
        let gab = max - min + 1
        return Math.floor(Math.random() * gab + min)
      } else {
        return 0
      }
    }
  }
}
</script>
<!-- <script setup>
import axios from 'axios'
import { onMounted } from 'vue'

onMounted(async () => {
  await getList()
})

async function getList() {
  const result = await axios.get('/mock/demo')
}
</script> -->

<style lang="scoped">
::v-deep .el-carousel__container {
  height: 100%;
}
.waterfall {
  column-count: 5; /* 设置列数 */
  column-gap: 20px; /* 设置列之间的间距 */
}

.waterfall-item {
  break-inside: avoid; /* 防止卡片跨列 */
  margin-bottom: 20px; /* 设置卡片之间的垂直间距 */
}
.el-tooltip__popper {
  pointer-events: none;
}
</style>
